const Service = require('egg').Service

class productService extends Service {
  get Product() {
    return this.ctx.model.Product
  }
  // 插入产品
  async insert(data) {
    const _data = await new this.Product(data)
    _data.save()
    return _data
  }

  // 查询产品
  async getList(body) {
    const pageNum = Number.parseInt(body.pageNum || 1)
    const pageSize = Number.parseInt(body.pageSize || 10)
    const titleReg = new RegExp(body.title,'ig')
    const filterParams = {}
    if(body.title) {
      filterParams.title = titleReg
    }
    if(body.menuId) {
      filterParams.menuId = body.menuId
    }
    const ret = await this.Product.find(filterParams,null,{
      sort: {createdAt: -1}
    }).skip((pageNum-1)*pageSize).limit(pageSize).populate('menuId', 'title').populate('imgs','link')
    const total = await this.Product.countDocuments(filterParams)
    return {
      list: ret,
      total
    }
  }
}

module.exports = productService